package com.weipai.springboot.module.util;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.UUID;

/**
 * 文件上传工具类
 *
 * @author LiHaiBo
 * @create 2017-12-29 13:31
 **/

public class UpdateFileUtil {

    public static String saveFiles(HttpServletRequest request, List<File> headPic, List<String> headPicFileName) throws IOException {

        //网络路径
        String basePath1 = request.getScheme()+"://"+request.getServerName()+":"
                +request.getServerPort() + request.getContextPath()+"/view/img/";
        //物理路径
        String filePath = request.getSession().getServletContext().getRealPath("/") + "/view/img/";

        StringBuffer sb = new StringBuffer();
        for(int i = 0 ; i < headPic.size() ; i++ )
        {
//            headPic.get(0).getName();
            String name = headPic.get(i).getName().substring(headPic.get(i).getName().indexOf("."),headPic.get(i).getName().length());
            String filename = new UpdateFileUtil().nonceStr()+name;

            if(headPic.size()==1){
                sb.append(basePath1+filename);
            }else{
                sb.append(basePath1+filename+",");
            }

            OutputStream os = new FileOutputStream(new File(filePath,filename));

            InputStream is = new FileInputStream(headPic.get(i));

            byte[] buf = new byte[1024];
            int length = 0 ;

            while(-1 != (length = is.read(buf) ) )
            {
                os.write(buf, 0, length) ;
            }
            is.close();
            os.close();
        }
        return new String(sb);
    }

    /**
     * 将网络图片转为Base64字符串
     * @param imgURL
     * @return
     */
    public static String GetImageStrFromUrl(String imgURL) {
        byte[] data = null;
        try {
            // 创建URL
            URL url = new URL(imgURL);
            // 创建链接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5 * 1000);
            InputStream inStream = conn.getInputStream();
            data = new byte[inStream.available()];
            inStream.read(data);
            inStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        // 返回Base64编码过的字节数组字符串
        return encoder.encode(data);
    }

    /**
     * 将本地图片转为Base64字符串
     * @param imgPath
     * @return
     */
    public static String GetImageStrFromPath(String imgPath) {
        InputStream in = null;
        byte[] data = null;
        // 读取图片字节数组
        try {
            in = new FileInputStream(imgPath);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        // 返回Base64编码过的字节数组字符串
        return encoder.encode(data);
    }

    /**
     * 将Base64字符串转为jpeg图片  本地
     * @param imgStr
     * @return
     */
    public static boolean GenerateImage(HttpServletRequest request, String imgStr) {
        if (imgStr == null) // 图像数据为空
            return false;
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            // Base64解码
            byte[] b = decoder.decodeBuffer(imgStr);
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {// 调整异常数据
                    b[i] += 256;
                }
            }
            // 生成jpeg图片
            String filename = new UpdateFileUtil().nonceStr()+".jpg";
            String imgFilePath = request.getSession().getServletContext().getRealPath("/") + "/view/img/"+filename;
            OutputStream out = new FileOutputStream(imgFilePath);
            out.write(b);
            out.flush();
            out.close();
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public String nonceStr(){

        return UUID.randomUUID().toString().toUpperCase().replaceAll("-", "");
    }

}
